package common;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

/**
 * 辅助集成测试，Spring AOP拦截器。
 * <li>保证在退出目标测试方法后，能够将Hibernate Session中的HQL同步到RDBMS，否则由于Session未同步会造成数据库锁死
 * 
 * @author worldheart
 */
public class HibernateFlushInterceptor implements MethodInterceptor {
	
    protected static final Log log 
    	= LogFactory.getLog(HibernateFlushInterceptor.class);

    //注入Hibernate 3.x SessionFactory
    private SessionFactory sessionFactory;

    public Object invoke(MethodInvocation invocation) throws Throwable {
    	log.info("beforeReturning()...." );
        Object object = invocation.proceed();
        Session session = SessionFactoryUtils.getSession(this.sessionFactory, false);
        if(session != null){
        	session.flush();
        }
        log.info("afterReturning()....");
        return object;
    }
    
    public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
    
}

